import qs from 'qs';
import axios from 'axios';
const http = {};
var vm = {};
if (typeof window !== 'undefined' && window.Vue) {
  vm = Vue.prototype;
} else {
  vm = window;
}

axios.interceptors.response.use( res => {
  let code = res.data.code ? res.data.code : 0;
  if (res.data.code) {
    if (res.data.code == '400') {
      vm.$message({
        type: 'info',
        message: 'session过期请重新登录!',
        duration: 3000
      });
      // 退出登录
      window.$toLogin()
    } else if (res.data.code == '500') {
      vm.$message({
        type: 'error',
        message: res.data.msg,
        showClose: true,
        duration: 3000
      });
    }
    return res;
  } else {
    return res;
  }
  }, error => {
    return Promise.reject(error);
  }
);
http.headers = {};
http.setHeaders = (headers = {}) => {
  http.headers = {...headers}
}
http.post = (url, data, formData = false, prefix, headers = {}) => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: (prefix ? prefix : SETING.BASE_URL) + url,
      data: formData ? qs.stringify(data) : data,
      headers: {
        ...http.headers,
        'N-Session-id': localStorage.getItem('session') || '',
        ...headers,
      },
      timeout: 100000
    }).then((res) => {
        if (res.data.code == '0') {
          resolve(res.data.data);
        } else if (res.data.status == '0') {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      }).catch((err) => {
        reject(err);
      });
  });
},
http.get = (url, data, fullPath = false, headers = {}) => {
  //申明一个promise
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: fullPath ? url : SETING.BASE_URL + url,
      params: data,
      headers: {
        ...http.headers,
        'N-Session-id': localStorage.getItem('session') || '',
        ...headers,
      },
      timeout: 100000
    }).then((res) => {
        if (res.data.code == '0') {
          resolve(res.data.data);
        } else if (res.data.status == '0') {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      }).catch((err) => {
        console.log(err)
        reject(err);
      });
  });
},
http.blob = (url, data, formData = false, headers = {}) => {
  // 申明一个promise
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: SETING.BASE_URL + url,
      data: formData ? qs.stringify(data) : data,
      responseType: 'blob',
      headers: {
        ...http.headers,
        'N-Session-id': localStorage.getItem('session') || '',
        ...headers,
      },
      timeout: 10000000
    }).then(res => {
      if (res) {
        var fileName = res.headers['content-disposition'].match(/filename=(.*)/gi)[0].split('=')[1];
        openDownloadDialog(res.data, fileName);
        resolve(res);
        } else {
          vm.$message({
            type: 'error',
            message: '导出内容为空',
          });
          reject(res.data);
        }
      }).catch((err) => {
        reject(err);
      });

  })
}
export default http

/**
 * 通用的打开下载对话框方法，没有测试过具体兼容性
 * @param url 下载地址，也可以是一个blob对象，必选
 * @param saveName 保存文件名，可选
 */
function openDownloadDialog(url, saveName) {
  if (typeof url == 'object' && url instanceof Blob) {
    // 创建blob地址
    url = URL.createObjectURL(url);
  }
  var aLink = document.createElement('a');
  aLink.href = url;
  aLink.download = decodeURI(saveName) || '';
  var event;
  if (window.MouseEvent) event = new MouseEvent('click');
  else {
    event = document.createEvent('MouseEvents');
    event.initMouseEvent(
      'click',
      true,
      false,
      window,
      0,
      0,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      0,
      null
    );
  }
  aLink.dispatchEvent(event);
}

/**
 * 通用的打开下载对话框方法，没有测试过具体兼容性
 * @param url 下载地址，也可以是一个blob对象，必选
 * @param saveName 保存文件名，可选
 */
function FileReaderDownload(url, saveName) {
  var reader = new FileReader();
  reader.readAsDataURL(url);
  reader.onload = function (e) {
    // 转换完成，创建一个a标签用于下载
    var a = document.createElement('a');
    a.download = decodeURI(saveName);
    var Url = e.target.result;
    a.href = Url;
    document.body.appendChild(a); // 修复firefox中无法触发click
    a.click();
    document.body.removeChild(a);
  };
}
